package com.xboss.tv.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hejunlin.tvsample.widget.AutoLayoutManager;
import com.hejunlin.tvsample.widget.MetroViewBorderImpl;
import com.xboss.tv.R;
import com.xboss.tv.adapter.MusicDataAdapter;
import com.xboss.tv.bean.Contacts;
import com.xboss.tv.bean.NewsBean;
import com.xboss.tv.listener.DataAPIListener;
import com.xboss.tv.net.DataAPIClient;
import com.xboss.tv.ui.MusicActivity;
import com.xboss.tv.view.SpaceItemDecoration;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017\7\23 0023.
 */

public class MusicDataFragment extends Fragment {

    private RecyclerView mRecyclerView;
    private MetroViewBorderImpl mMetroViewBorderImpl;
    private Activity activity;
    public StrProcessor parser;
    private OnDataFinishedListener mOnDataFinishedListener;

    public static interface StrProcessor {

        void OnParserJsonString(JSONObject response);
    }

    public static interface OnDataFinishedListener {
        void onPerformData();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.music_layout_content, container, false);

        activity = getActivity();

        parser = new StrProcessor() {
            @Override
            public void OnParserJsonString(JSONObject response) {
                parseJson(response);
            }
        };

        mOnDataFinishedListener = new OnDataFinishedListener() {
            @Override
            public void onPerformData() {
                initUI(view);
            }
        };

        initData("5");

        return view;
    }

    private void initUI(View view) {

        mMetroViewBorderImpl = new MetroViewBorderImpl(activity);
        mMetroViewBorderImpl.setBackgroundResource(R.drawable.border_color);

        mRecyclerView = (RecyclerView) view.findViewById(R.id.music_recycler_view);

        GridLayoutManager gridlayoutManager = new AutoLayoutManager(activity, 4);
        gridlayoutManager.setOrientation(GridLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(gridlayoutManager);
        mRecyclerView.setFocusable(false);
        mMetroViewBorderImpl.attachTo(mRecyclerView);

        mRecyclerView.addItemDecoration(new SpaceItemDecoration(4,
                getResources().getDimensionPixelSize(R.dimen.music_padding_middle), true));

        MusicDataAdapter adapter = new MusicDataAdapter(activity, mNewsData);
        mRecyclerView.setAdapter(adapter);

        adapter.setOnMenuitemClickListener(new MusicDataAdapter.OnMenuitemClickListener() {

            @Override
            public void onItemClick(String url, int position) {
                if (Contacts.isLoad) {

                    NewsBean newsBean = mNewsData.get(position);

                    Intent intent = new Intent(activity, MusicActivity.class);
                    intent.putExtra("url", newsBean.url);
                    intent.putExtra("pic", newsBean.pic);
                    intent.putExtra("name", newsBean.src);
                    startActivity(intent);

                    //                    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
//
//                    View view = LayoutInflater.from(activity).inflate(R.layout.dialog_music_item, null);
//
//                    WebView webview = (WebView) view.findViewById(R.id.dialog_music_webview);
//                    webview.loadUrl(url);
//
//                    builder.setView(view);
//
//                    AlertDialog dialog = builder.create();
//                    dialog.show();
//
//                    //放在show()之后，不然没有效果
//                    Window dialogWindow = dialog.getWindow();
//                    WindowManager m = activity.getWindowManager();
//                    Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
//                    WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
//                    //设置高度和宽度
//                    p.height = (int) (d.getHeight() * 0.4); // 高度设置为屏幕的0.6
//                    p.width = (int) (d.getWidth() * 0.6); // 宽度设置为屏幕的0.65
//                    //设置位置
//                    p.gravity = Gravity.BOTTOM;
//                    //设置透明度
//                    p.alpha = 0.5f;
//                    dialogWindow.setAttributes(p);

                    Contacts.isLoad = false;
                }
            }

            @Override
            public void onBackClick(Activity activity) {
                activity.finish();
            }
        });
    }

    private void initData(String topid) {

        Map<String, String> params = new LinkedHashMap<>();
        params.put("topid", topid);

        DataAPIClient.doHttpHeadersRequest(activity, Contacts.qqmusic_url, params, new DataAPIListener() {
            @Override
            public void onSuccess(JSONObject response) {
                parser.OnParserJsonString(response);
            }

            @Override
            public void onFailure(String errorMsg) {
                Toast.makeText(activity, "查询数据失败，失败数据为:" + errorMsg, Toast.LENGTH_SHORT).show();
                activity.finish();
            }
        });
    }

    private List<NewsBean> mNewsData;

    private void parseJson(JSONObject response) {

        JSONObject jsonObject = response.getJSONObject("showapi_res_body").getJSONObject("pagebean");
        JSONArray list = jsonObject.getJSONArray("songlist");
        mNewsData = new ArrayList<>();
        mNewsData.clear();

        for (int i = 0; i < list.size(); i++) {

            NewsBean bean = new NewsBean();
            JSONObject object = list.getJSONObject(i);
            bean.url = object.getString("url");
            bean.pic = object.getString("albumpic_big");
            bean.src = object.getString("singername");
            mNewsData.add(bean);
        }

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mOnDataFinishedListener.onPerformData();
            }
        });
    }
}
